package com.pomr.controller.receive;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import com.pomr.entity.EquipmentApc;
import com.pomr.entity.PersonMsg;
import com.pomr.entity.ReceiveEntity;
import com.pomr.entity.ReceiveParam;
import com.pomr.model.sys.FaultTreatment;
import com.pomr.util.common.IdcardUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * 设备领取
 * @author Administrator
 *
 */
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pomr.model.equipmentstorage.EquipmentStorage;
import com.pomr.model.equipmentstorage.EquipmentStorageDetail;
import com.pomr.model.equipmentstorage.MonitoringData;
import com.pomr.model.equipmentstorage.Receive;
import com.pomr.model.equipmentstorage.ReceiveRecipt;
import com.pomr.model.health.Option;
import com.pomr.model.health.PersonRecord;
import com.pomr.model.menu.EquipmentCondition;
import com.pomr.model.menu.EquipmentStatus;
import com.pomr.model.simstorage.SimStorageDetail;
import com.pomr.model.sys.Province;
import com.pomr.model.sys.User;
import com.pomr.service.equipmentreceive.ReceiveService;
import com.pomr.util.common.CommonData;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
import com.pomr.util.page.PageParam;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Controller
@RequestMapping("/receive")
public class ReceiveController {
	@Autowired
	@Qualifier("receiveServiceImpl")
	private ReceiveService receiveService;
	
	/**
	 * 通过身份证号或者姓名查询个人档案
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchRecords",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchRecordByCon(@RequestBody Map<String, String> map, HttpServletRequest request){
		ResponseData pd = null;
		try {
			User user = JWT.findUserByToken(request);
			if(user.getAgency() == null){
				pd = ResponseData.custom("机构下无档案可用");
				return pd;
			}
			String rs = map.get("rs");
			if(rs==null || "".equals(rs)){
				pd = ResponseData.custom("查询条件不能为空");
			}else{
				List<PersonRecord> records = receiveService.searchRecords(rs,user);
				pd = ResponseData.ok();
				pd.putDataValue("records", records);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 添加前查询 （设备、sim卡）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-addbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData addBefore(HttpServletRequest request){
		ResponseData pd = null;
		try {
			User user = JWT.findUserByToken(request);
			if(user.getAgency() == null){
				pd = ResponseData.custom("用户不属于任一家机构");
				return pd;
			}
			pd = ResponseData.ok();
			//查询设备
			List<EquipmentStorageDetail> equipments = receiveService.searchEquipments(user);
			pd.putDataValue("equipments", equipments);
			//查询sim卡信息
			List<SimStorageDetail> sims = receiveService.searchSims(user);
			pd.putDataValue("sims", sims);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 领用设备
	 * @param receiveEnt
	 * @return
	 */
	@RequestMapping(value="/inter-add",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData addReceive(@RequestBody ReceiveEntity receiveEnt, HttpServletRequest request){
		ResponseData pd = null;
		System.out.println(receiveEnt.getRecords().size());
		try {
			if(receiveEnt==null || receiveEnt.getReceive()==null){
				pd = ResponseData.custom("数据不完整");
				return pd;
			}
			Receive receive = receiveEnt.getReceive();
			if(receive.getRecord()==null || receive.getMatch().getEquipmentdetail()==null || receive.getMatch().getSimdetail()==null){
				pd = ResponseData.custom("数据不完整");
			}else{
				User user = JWT.findUserByToken(request);
				int  kid = receiveService.addReceive(user, receiveEnt);//保存失败 直接抛出异常
				pd = ResponseData.ok();
				//查询收据信息
				ReceiveRecipt receipt = receiveService.searchReceipt(kid);
				pd.putDataValue("receipt", receipt);
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.custom("数据处理异常，"+e.getMessage());
		}
		return pd;
	}
	
	/**
	 * 查询前 获取机构设备信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchBefore(HttpServletRequest request){
		ResponseData pd = null;
		try {
			User user = JWT.findUserByToken(request);
			if(user.getAgency() == null){
				pd = ResponseData.custom("用户不属于任一家机构");
				return pd;
			}
			pd = ResponseData.ok();
			//查询设备
			List<EquipmentStorageDetail> equipments = receiveService.searchEquipmentsUsed(user);
			pd.putDataValue("equipments", equipments);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 查询设备领用情况
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-search",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<Receive>> searchReceives(PageParam param, HttpServletRequest request){
		try{
			String re = param.getParams().get("name");//姓名或身份证号
			String detailid = param.getParams().get("equipemnt");//设备库存明细id
			String page = param.getPage();
			String limit = param.getLimit();
			User user = JWT.findUserByToken(request);
			return receiveService.searchReceives(re, detailid, page, limit, user);
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 设备领取详细信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchone",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchReceiceById(@RequestBody Receive receive,HttpServletRequest request){
		ResponseData pd = null;
		try{
			receive = receiveService.searchReceiveById(receive);
			if(receive!=null){
				pd = ResponseData.ok();
				pd.putDataValue("receive", receive);
				List<EquipmentCondition> es = (List<EquipmentCondition>) CommonData.data.get("EquipmentCondition");
				pd.putDataValue("equipmentCondition", es);
			}else{
				pd = ResponseData.custom("未找到信息");
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 设备归还
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-back",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData backhReceiceById(@RequestBody Map<String, String> map,HttpServletRequest request) throws Exception{
		ResponseData pd = null;
		User user = JWT.findUserByToken(request);
		String id = map.get("id");
		String isjb = map.get("isjb");
		if(receiveService.backReceiveById(id,isjb,user)){
			pd = ResponseData.ok();
		}else{
			pd = ResponseData.custom("操作失败");
		}
		return pd;
	}
	
	/**
	 * 设备领用信息更新
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-edit",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editReceiceById(@RequestBody Receive receive,HttpServletRequest request){
		ResponseData pd = null;
		try{
			if(receiveService.editReceiveById(receive)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.custom("操作失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 设备领用获取定金
	 * @return
	 */
	@RequestMapping(value="/inter-searchMoney",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchMoney(@RequestBody Map<String, String> map){
		ResponseData pd = null;
		try{
			String sbid = map.get("sbid");
			String simid = map.get("simid");
			double money = receiveService.searchMonry(sbid, simid);
			pd = ResponseData.ok();
			pd.putDataValue("money", money);
		}catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	@RequestMapping(value="/searchre",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchRecords(@RequestBody Map<String, String> map){
		ResponseData pd = null;
		try {
			String cond = map.get("cond");
			List<PersonRecord> records = receiveService.searchRecords(cond);
			pd = ResponseData.ok();
			pd.putDataValue("records", records);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	
	@RequestMapping(value="/searchreceive",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchReceives(@RequestBody Map<String, String> map){
		ResponseData pd = null;
		try {
			String id = map.get("reid");
			List<EquipmentStorage> receives = receiveService.searchReceives(id);
			pd = ResponseData.ok();
			pd.putDataValue("receives", receives);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 同步获取数据返回页面 --通过身份证号
	 * @return
	 */
	@RequestMapping(value="/searchcon",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView searchRecordsByCon(String cond,String time1,String time2,ModelAndView m){
		try {
		//	String cond = map.get("cond");
			System.out.println(cond);
			List<EquipmentStorage> receives = receiveService.searchReceivesByCon(cond);
			m.setViewName("health/hdata");
			m.addObject("receives", receives);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return m;
	}
	
	@RequestMapping(value="/searchmonitor",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchMonitors(@RequestBody Map<String, String> map){
		ResponseData pd = null;
		try {
			String id = map.get("reid");
			String pid = map.get("pid");
			String time1 = map.get("time1");
			String time2 = map.get("time2");
			Option opt = receiveService.searchMonitors(id,pid,time1,time2);
			if(opt == null){
				pd = ResponseData.custom("没有监测数据");
			}else{
				pd = ResponseData.ok();
				pd.putDataValue("opt", opt);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	/**
	 * 通过设备id获取绑定的sim卡信息
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/inter-searchBindSim",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchBindSim(@RequestBody Map<String, String> map,HttpServletRequest request) throws Exception{
		ResponseData pd = ResponseData.ok();
		String eid = map.get("id");
		SimStorageDetail detail = receiveService.seachBindSim(eid);
		if(detail!=null){
			pd.putDataValue("detail", detail);
		}
		return pd;
	}
	
	/**
	 * 通过sim卡id获取绑定的设备信息
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/inter-searchBindEquip",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchBindEquip(@RequestBody Map<String, String> map,HttpServletRequest request) throws Exception{
		ResponseData pd = ResponseData.ok();
		String eid = map.get("id");
		EquipmentStorageDetail detail = receiveService.seachBindEquip(eid);
		if(detail!=null){
			pd.putDataValue("detail", detail);
		}
		return pd;
	}
	
	/**
	 * 查询对应的绑定信息
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/inter-searchBind",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchBind(@RequestBody Map<String, String> map,HttpServletRequest request) throws Exception{
		ResponseData pd = ResponseData.ok();
		String type = map.get("type");
		User user = JWT.findUserByToken(request);
		Map<String, Object> maps = receiveService.searchBind(type, user);
		for(Entry<String, Object> m:maps.entrySet()){
			pd.putDataValue(m.getKey(), m.getValue());
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-searchSimByEqui",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchSimByEqui(@RequestBody Map<String, String> map,HttpServletRequest request) throws Exception{
		ResponseData pd = ResponseData.ok();
		String eid = map.get("eid");
		pd.putDataValue("sim", receiveService.searchSimByEqui(eid));
		return pd;
	}

	/**
	 * 获取本机构设备绑定用户
	 * @param param
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchPersons",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchReceivePersons(PageParam param, HttpServletRequest request){
		try{
			String re = param.getParams().get("name");//身份证号
			String page = param.getPage();
			String limit = param.getLimit();
			User user = JWT.findUserByToken(request);
			return receiveService.searchReceivePersons(re, page, limit, user);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取用户绑定过的设备
	 * @param param
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchEquipByPerson",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<EquipmentStorage>> searchEquipByPerson(PageParam param, HttpServletRequest request){
		try{
			String re = param.getParams().get("pid");//用户ID或者身份证号
			String page = param.getPage();
			String limit = param.getLimit();
			return receiveService.searchEquipByPerson(re, page, limit);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取用户设备监测数据
	 * @return
	 */
	@RequestMapping(value="/inter-searchMonitorsByEquip",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchMonitorsByEquip(HttpServletRequest request, @RequestBody Map<String,String> map){
		ResponseData pd = null;
		try{
			String idcard = map.get("idcard");
			String eid = map.get("eid");
			String time1 = map.get("time1");
			String time2 = map.get("time2");
			Option opt = receiveService.searchMonitorsByEquip(eid, idcard, time1,time2);
			if(opt == null){
				pd = ResponseData.custom("没有监测数据");
			}else{
				pd = ResponseData.ok();
				pd.putDataValue("opt", opt);
			}
		}catch (Exception e){
			e.printStackTrace();
			pd = ResponseData.custom(e.getMessage());
		}
		return pd;
	}


	/**
	 * 获取机构下的设备列表
	 * @param param
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchEquipOfAgency",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<EquipmentStorage>> searchEquipOfAgency(PageParam param, HttpServletRequest request){
		try{
			String page = param.getPage();
			String limit = param.getLimit();
			User user = JWT.findUserByToken(request);
			return receiveService.searchEquipOfAgency(page, limit, user);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取设备领用的用户
	 * @param param 身份证号
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/inter-searchPersonsOfEquip",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<PersonRecord>> searchPersonsOfEquip(PageParam param, HttpServletRequest request){
		try{
			String re = param.getParams().get("name");//身份证号
			String eid = param.getParams().get("eid");//设备编号
			String page = param.getPage();
			String limit = param.getLimit();
			return receiveService.searchPersonsOfEquip(re, eid, page, limit);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping(value="/inter-searchFlowsWithReceive",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchFlowsWithReceive(HttpServletRequest request, @RequestBody Map<String,String> map) throws Exception{
		ResponseData pd = ResponseData.ok();
		String rid = map.get("rid");
		pd.putDataValue("sim",receiveService.searchSimDetail(rid));
		return pd;
	}

	/**
	 * 设备申领
	 * 记录申领人信息，并将申领信息记入消息中心
	 * @param pname  申领人姓名
	 * @param pidcard  申领人身份证号
	 * @param euipmentid 申领设备编号
	 * @param agencyid 申领机构编号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/app-application",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData equipApplication(String pname, String pidcard, String euipmentid ,String agencyid){
		ResponseData pd = null;
		try{
			if(pname==null || "".equals(pname)){
				pd = ResponseData.custom("请上传领用人姓名");
			}else if(pidcard==null || "".equals(pidcard)){
				pd = ResponseData.custom("请上传领用人身份证号");
			}else if(euipmentid==null || "".equals(euipmentid)){
				pd = ResponseData.custom("请上传领用设备编号");
			}else if(agencyid==null || "".equals(agencyid)){
				pd = ResponseData.custom("请上传申领机构编号");
			}else{
				PersonMsg personMsg = new PersonMsg();
				personMsg.setName(pname);
				personMsg.setIdcard(pidcard);
				EquipmentApc apc = new EquipmentApc();
				apc.setPerson(personMsg);
				apc.setEuipmentid(euipmentid);
				apc.setAgencyid(agencyid);
				if(IdcardUtils.validateCard(apc.getPerson().getIdcard())){
					int status = receiveService.application(apc);
					if(status == 1){
						pd = ResponseData.ok();
					}else if(status == 3){
						pd = ResponseData.custom("申领人档案已停用");
					}else if(status == 4){
						pd = ResponseData.custom("申领人档案显示已死亡");
					}else{
						pd = ResponseData.custom("未知错误");
					}
				}else{
					pd = ResponseData.custom("身份证号不合法");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			pd= ResponseData.custom(e.getMessage());
		}
		return pd;
	}
	@RequestMapping(value="/inter-fault",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData fault(@RequestBody FaultTreatment faultTreatment, HttpServletRequest request) throws Exception{
		faultTreatment.setCreateUserId(JWT.findUserByToken(request).getId());
		faultTreatment.setUpdateUserId(JWT.findUserByToken(request).getId());
		return receiveService.fault(faultTreatment);
	}

	@RequestMapping(value="/inter-searchfault",method=RequestMethod.GET)
	@ResponseBody
	public ResponseData searchfault(String receiveid) throws Exception{
		return receiveService.searchfault(receiveid);
	}

	@RequestMapping(value="/inter-editfault",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editfault(@RequestBody FaultTreatment faultTreatment, HttpServletRequest request) throws Exception{
		faultTreatment.setUpdateUserId(JWT.findUserByToken(request).getId());
		return receiveService.editfault(faultTreatment);
	}

	@RequestMapping(value="/inter-receivel",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData receiveEquipment(@RequestBody ReceiveParam receiveParam, HttpServletRequest request) throws Exception{
		User user = JWT.findUserByToken(request);
		ResponseData pd =  receiveService.addReceive(user, receiveParam);
		if(pd.getCode() == 200){
			//查询收据信息
			ReceiveRecipt receipt = receiveService.searchReceipt((Integer) pd.getData().get("rid"));
			pd.putDataValue("receipt", receipt);
		}
		return pd;
	}

}
